package com.XDApp.xdbase.activitys;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.XDApp.xdbase.BaseActivity;
import com.XDApp.xdbase.BaseApplication;
import com.XDApp.xdbase.XDHttpClient;
import com.XDApp.xdbase.adapter.PhotosAdapter;
import com.XDApp.xdbase.bean.Comment;
import com.XDApp.xdbase.bean.Order;
import com.XDApp.xdbase.bean.PicUrl;
import com.XDApp.xdbase.bean.SeneryEntity;
import com.XDApp.xdbase.utils.CommonUtil;
import com.XDApp.xdbase.utils.HttpProtocol;
import com.XDApp.xdbase.utils.HttpProtocol.PRODUCT_TYPE;
import com.XDApp.xdbase.utils.IRequest;
import com.XDApp.xdbase.utils.SharePopupWindow;
import com.XDApp.xdbase.utils.xdConfig;
import com.XDApp.xdbase.view.CRToast;
import com.XDApp.xdbase.xinsilu.R;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.umeng.socialize.controller.RequestType;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.UMSsoHandler;

/**
 * 自由行详情页
 * 
 * @author Administrator
 */
public class FreeWalkerDetailActivity extends BaseActivity implements OnClickListener {
	final UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.share",
			RequestType.SOCIAL);
	private final String TAG = "FreeWalkerDetailActivity";
	private final int PARAM_TIMER = 0;
	private final int TIMER_DELAY = 5000;
	private ListView listView;
	private WebView wv_introduce;// 行程说明
	private ImageView openText;
	private RelativeLayout product_feature;// 产品特色
	private RelativeLayout cost;// 费用说明
	private RelativeLayout hint;// 重要提示
	private RelativeLayout comment;// 用户点评
	private TextView title;
	private ImageView iv_back;

	private ViewPager viewPager;
	private LinearLayout llPoints;
	private final boolean isLoop = true;

	private boolean showMore = true;
	private String seneryID;
	private String flag;
	private String costs;// 票价
	private List<PicUrl> picURLs;// 轮播图URL
	private List<Order> orderList;// 轮播图URL
	private List<Comment> commentList;// 评论列表
	private String importantTips;// 重要提示
	private String productFeatures;// 产品特色
	private String tripIntroduce;// 行程说明
	private String ticketTitle;// 景点标题
	private View mCollect;

	private int mPhotosSize;

	private View[] mPlanViews = new View[3];

	private final Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
			sendEmptyMessageDelayed(PARAM_TIMER, TIMER_DELAY);
		}
	};
	private Intent intent;

	@Override
	protected void initViews() {
		setContentView(R.layout.freewalker_detail_activity);

		findViewById(R.id.iv_share).setVisibility(View.VISIBLE);
		findViewById(R.id.iv_store).setVisibility(View.VISIBLE);
		findViewById(R.id.iv_share).setOnClickListener(this);
		mCollect = findViewById(R.id.iv_store);
		mCollect.setOnClickListener(this);

		viewPager = (ViewPager) findViewById(R.id.vPager);
		llPoints = (LinearLayout) findViewById(R.id.ll_points);
		seneryID = getIntent().getStringExtra("seneryID");
		flag = getIntent().getStringExtra("flag");
		listView = (ListView) findViewById(R.id.lv_freedetail);
		wv_introduce = (WebView) findViewById(R.id.wv_way_introduce);
		openText = (ImageView) findViewById(R.id.iv_introduce);
		title = (TextView) findViewById(R.id.title_text);
		iv_back = (ImageView) findViewById(R.id.title_back);

		product_feature = (RelativeLayout) findViewById(R.id.rl_product_feature);
		cost = (RelativeLayout) findViewById(R.id.rl_cost_description);
		hint = (RelativeLayout) findViewById(R.id.rl_hint);
		comment = (RelativeLayout) findViewById(R.id.rl_comment);
	}

	@Override
	protected void initEvents() {
		if ("0".equals(flag)) {
			title.setText("自由行");
		} else if ("1".equals(flag)) {
			title.setText("参团游");
		}
		openText.setOnClickListener(this);
		iv_back.setOnClickListener(this);
		product_feature.setOnClickListener(this);
		cost.setOnClickListener(this);
		hint.setOnClickListener(this);
		comment.setOnClickListener(this);
		handler.sendEmptyMessageDelayed(PARAM_TIMER, TIMER_DELAY);

		sharePopupWindow = new SharePopupWindow(mContext, View.inflate(mContext, R.layout.popup1, null),
				getResources().getDisplayMetrics().widthPixels, LayoutParams.WRAP_CONTENT);

		getData();
	}

	@Override
	public void onClick(View v) {
		intent = new Intent(FreeWalkerDetailActivity.this, FreeWalkerDataActivity.class);
		switch (v.getId()) {
		case R.id.rl_product_feature:// 产品特色
			intent.putExtra("data", productFeatures);
			intent.putExtra("type", 0);
			startActivity(intent);
			break;
		case R.id.rl_cost_description:// 费用说明
			intent.putExtra("data", costs);
			intent.putExtra("type", 1);
			startActivity(intent);
			break;
		case R.id.rl_hint:// 重要提示
			intent.putExtra("data", importantTips);
			intent.putExtra("type", 2);
			startActivity(intent);
			break;
		case R.id.rl_comment:// 用户点评
			Intent intent1 = new Intent(FreeWalkerDetailActivity.this, UserCommentActivity.class);
			ArrayList list = new ArrayList();
			list.add(commentList);
			intent.putExtra("commentList", list);
			startActivity(intent1);
			break;

		case R.id.iv_introduce:
			if (showMore) {
				showMore = false;
				wv_introduce.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
						LayoutParams.WRAP_CONTENT));
				wv_introduce.loadData(tripIntroduce, "text/html; charset=UTF-8", null);
				openText.setImageResource(R.drawable.text_close);

			} else {
				wv_introduce.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 200));
				wv_introduce.loadData(tripIntroduce, "text/html; charset=UTF-8", null);
				openText.setImageResource(R.drawable.text_open);
				showMore = true;
			}
			break;
		case R.id.title_back:
			if (sharePopupWindow.isShowing()) {
				sharePopupWindow.dismiss();
			} else
				finish();
			break;
		case R.id.iv_share:
			if (BaseApplication.getApplication().isLogin()) {
				sharePopupWindow.setInfors(mController, "shareTitle", "shareContent", "http://www.baidu.com");
				sharePopupWindow.showAtLocation(findViewById(R.id.title_back), Gravity.BOTTOM, 0, 0);
			} else {
				CommonUtil.showToast(mContext, "尚未登录，请先登录!");
				Intent intent = new Intent(FreeWalkerDetailActivity.this, LoginActivity.class);
				startActivity(intent);
			}
			break;
		case R.id.iv_store:// 收藏
			if (BaseApplication.getApplication().isLogin()) {
				collect();
			} else {
				CommonUtil.showToast(mContext, "尚未登录，请先登录!");
				Intent intent = new Intent(FreeWalkerDetailActivity.this, LoginActivity.class);
				startActivityForResult(intent, 100);
			}
			break;
		default:
			break;
		}
	}

	private void collect() {
		mCollect.setEnabled(false);
		if (mCollect.isSelected()) {
			HttpProtocol.cancelCollect(seneryID, BaseApplication.getApplication().getUser().getUserID(),
					flag.equals("0") ? PRODUCT_TYPE.TRAVEL.type : PRODUCT_TYPE.FREEWALKER.type,
					new IRequest<Boolean>() {

						@Override
						public void request(Boolean t) {
							if (t) {
								CRToast.show(mContext, "取消收藏成功！");
								mCollect.setSelected(false);
							} else {
								CRToast.show(mContext, "取消收藏失败！");
							}
							mCollect.setEnabled(true);
						}
					});
		} else {
			HttpProtocol.addCollect(seneryID, BaseApplication.getApplication().getUser().getUserID(),
					flag.equals("0") ? PRODUCT_TYPE.TRAVEL.type : PRODUCT_TYPE.FREEWALKER.type,
					new IRequest<Boolean>() {

						@Override
						public void request(Boolean t) {
							if (t) {
								CRToast.show(mContext, "添加收藏成功！");
								mCollect.setSelected(true);
							} else {
								CRToast.show(mContext, "添加收藏失败！");
							}
							mCollect.setEnabled(true);
						}
					});
		}
	}

	// TODO 访问网络获取数据
	private void getData() {
		if (CommonUtil.checkNetState(mContext)) {
			RequestParams params = new RequestParams();
			params.put("flag", flag);
			params.put("seneryId", seneryID);

			XDHttpClient.post(xdConfig.GET_FREETOURDETAIL, params, new AsyncHttpResponseHandler() {
				@Override
				public void onSuccess(int statusCode, String content) {
					findViewById(R.id.loading).setVisibility(View.GONE);
					Log.e(TAG, content);

					JSONObject obj = new JSONObject().parseObject(content);
					String data = obj.getString("data");
					if (TextUtils.isEmpty(data)) {
						CommonUtil.showToast(mContext, "获取数据失败");
						return;
					}

					SeneryEntity entity = JSON.parseObject(data, SeneryEntity.class);
					Log.i(TAG, data);

					// 判断返回数据是否正确
					if (null != entity) {
						List<Comment> list = entity.getList();// 评论集合
						picURLs = entity.getPicURLs();
						List<String> str = new ArrayList<String>();
						for (int i = 0; i < picURLs.size(); i++) {
							str.add(picURLs.get(i).getUrl());
						}
						mPhotosSize = picURLs.size();
						orderList = entity.getOrderList();
						mPlanViews = new View[picURLs.size()];
						importantTips = entity.getImportantTips();
						costs = entity.getCosts();
						productFeatures = entity.getProductFeatures();
						tripIntroduce = entity.getTripIntroduce();

						JSONObject obj1 = new JSONObject().parseObject(entity.getOrderTitle());
						ticketTitle = obj1.getString("title");
						if (tripIntroduce.length() > xdConfig.MAX_LENGTH) {
							openText.setVisibility(View.VISIBLE);
						} else {
							openText.setVisibility(View.GONE);
						}
						wv_introduce.loadData(tripIntroduce, "text/html; charset=UTF-8", null);
						for (int i = 0; i < picURLs.size(); i++) {
							View view = View.inflate(mContext, R.layout.item_plan, null);
							mPlanViews[i] = view;
							llPoints.addView(view);
						}
						if (str.size() > 0) {
							PhotosAdapter adapter = new PhotosAdapter(FreeWalkerDetailActivity.this, str);
							viewPager.setAdapter(adapter);
							viewPager.setOnPageChangeListener(mOnPageChangeListener);
						}
						setPagerSelected(0);
						PriceAdapter priceAdapter = new PriceAdapter(orderList, ticketTitle);
						listView.setAdapter(priceAdapter);
					} else {
						CommonUtil.showToast(mContext, "获取数据失败");
					}
				}

				@Override
				public void onFailure(Throwable arg0, String arg1) {
					super.onFailure(arg0, arg1);
					CommonUtil.showToast(mContext, "获取数据失败");
					// Toast.makeText(mContext, R.string.pLease_check_network,
					// 0).show();
				}
			});

			if (BaseApplication.getApplication().isLogin()) {
				HttpProtocol.isCollect(this.seneryID, BaseApplication.getApplication().getUser().getUserID(),
						flag.equals("0") ? 1 : 0, new IRequest<Boolean>() {

							@Override
							public void request(Boolean t) {
								if (t) {
									mCollect.setSelected(true);
								} else {
									mCollect.setSelected(false);
								}
							}
						});
			}

		} else {
			Toast.makeText(mContext, R.string.pLease_check_network, 0).show();
		}
	}

	private void setPagerSelected(int position) {
		for (int i = 0; i < mPlanViews.length; i++) {
			if (position == i) {
				mPlanViews[i].setSelected(true);
			} else {
				mPlanViews[i].setSelected(false);
			}
		}
	}

	private final OnPageChangeListener mOnPageChangeListener = new OnPageChangeListener() {

		@Override
		public void onPageSelected(int position) {
			setPagerSelected(position % mPhotosSize);
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
		}
	};
	private SharePopupWindow sharePopupWindow;

	private class PriceAdapter extends BaseAdapter {
		private final List<Order> priceList;
		private final String title;

		private PriceAdapter(List<Order> priceList, String title) {
			this.priceList = priceList;
			this.title = title;
		}

		@Override
		public int getCount() {
			return priceList.size();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertion, ViewGroup arg2) {
			PriceHolder holder = null;
			final Order order = priceList.get(position);
			if (null == convertion) {
				holder = new PriceHolder();
				convertion = View.inflate(FreeWalkerDetailActivity.this, R.layout.item_price_pay_freewalker,
						null);
				holder.price = (TextView) convertion.findViewById(R.id.price);
				holder.normalPrice = (TextView) convertion.findViewById(R.id.normal_price);
				holder.title = (TextView) convertion.findViewById(R.id.title);
				holder.reserve = (Button) convertion.findViewById(R.id.reserve);

				convertion.setTag(holder);
			} else {
				holder = (PriceHolder) convertion.getTag();
			}
			holder.price.setText("￥" + order.getVipPrice());
			holder.normalPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
			holder.normalPrice.setText("￥" + order.getNormalPrice());
			holder.title.setText(ticketTitle);
			holder.reserve.setOnClickListener(new OnClickListener() {// TODO
																		// 跳转到预订界面
						@Override
						public void onClick(View v) {
							if (!mApplication.isLogin()) {
								Intent intent1 = new Intent(mContext, LoginActivity.class);
								startActivity(intent1);
							} else {
								Intent intent = new Intent(FreeWalkerDetailActivity.this,
										ReservationActivity.class);
								intent.putExtra("type", 0);
								intent.putExtra("price", order.getVipPrice());
								intent.putExtra("title", title);
								intent.putExtra("id", order.getOrderId());
								startActivity(intent);
							}
						}
					});

			return convertion;
		}
	}

	class PriceHolder {
		Button reserve;
		TextView price;
		TextView normalPrice;
		TextView title;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 100) {
			HttpProtocol.isCollect(this.seneryID, BaseApplication.getApplication().getUser().getUserID(),
					flag.equals("0") ? 1 : 0, new IRequest<Boolean>() {

						@Override
						public void request(Boolean t) {
							if (t) {
								mCollect.setSelected(true);
							} else {
								mCollect.setSelected(false);
							}
						}
					});
		}

		UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler(requestCode);
		if (ssoHandler != null) {
			ssoHandler.authorizeCallBack(requestCode, resultCode, data);
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (sharePopupWindow.isShowing()) {
			sharePopupWindow.dismiss();
			return false;
		} else
			return super.onKeyDown(keyCode, event);
	}
}
